package com.esapi.api;

import cn.hutool.json.JSONUtil;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

public class TestIndexApi {

    private static RestHighLevelClient client;

    static {
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
    }

    /**
     *  创建索引
     * @throws IOException
     */
    public static void createIndex() throws IOException {

        CreateIndexRequest request = new CreateIndexRequest("java-api");

        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);

        System.out.println(response.index());
    }

    /**
     *  查询索引   当索引不存在会报错  ElasticsearchStatusException
     * @throws IOException
     */
    public static void queryIndex()  {

        try {
            GetIndexRequest request = new GetIndexRequest("java-api");

            GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);

            System.out.println(JSONUtil.toJsonStr(response));
        }catch (ElasticsearchStatusException | IOException e){
            System.out.println(e.getLocalizedMessage());
        }

    }

    /**
     *  删除索引
     * @throws IOException
     */
    public static void deleteIndex() throws IOException {

        DeleteIndexRequest request = new DeleteIndexRequest("java-api");

        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);

        System.out.println(JSONUtil.toJsonStr(response));
    }


    public static void main(String[] args) throws IOException {
        // 创建索引
        //createIndex();

        // 查询索引
        queryIndex();

        // 删除索引
        //deleteIndex();

        client.close();
    }
}
